<?php
/**
 * Created by PhpStorm.
 * User: xutao
 * Date: 2018/11/8
 * Time: 15:48
 */
//菜单数据库
namespace app\admin\model;


use think\Loader;
use think\Model;

class AuthRules extends Model{
    protected $table = 'auth_rule';
    protected $autoWriteTimestamp = 'datetime';


    //获取菜单列表
    public static function get_meun($ids){
        if($ids){
            $re = self::where('id','in',$ids)->where('status',1)->order('sort desc')->select();
        }else{
            $re = self::where('status',1)->order('sort desc')->select();
        }
        $data = tree($re);
        return $data;
    }
    //获取列表
    public static function get_all(){

        $re = self::order('sort desc')->select();
        $data = one_tree($re);
        return $data;
    }

    //添加
    public function add($data){
        //验证
        $AuthrulesValidate = Loader::validate('AuthrulesValidate');
        if(!$AuthrulesValidate->check($data)) return json(['code'=>2,'data'=>'','msg'=>$AuthrulesValidate->getError()]);
        //检测该验证规则是否存在
        $is_cuznai = self::where('name',$data['name'])->find();
        if($is_cuznai) return json(['code'=>3,'data'=>'','msg'=>'该菜单已存在']);
        $add = $this->allowField(true)->save($data);
        if($add) return json(['code'=>200,'data'=>$add,'msg'=>'添加成功']);
        return json(['code'=>4,'data'=>'','msg'=>'添加失败']);
    }


    //修改
    public function edit($data){
        //验证
        $AuthrulesValidate = Loader::validate('AuthrulesValidate');
        if(!$AuthrulesValidate->check($data)) return json(['code'=>2,'data'=>'','msg'=>$AuthrulesValidate->getError()]);
        //检测该验证规则是否存在
        $is_cuznai = self::where('name',$data['name'])->where('id','<>',$data['id'])->find();
        if($is_cuznai) return json(['code'=>3,'data'=>'','msg'=>'该菜单已存在']);
        $add = $this->allowField(true)->save($data,['id'=>$data['id']]);
        if($add) return json(['code'=>200,'data'=>$add,'msg'=>'修改成功']);
        return json(['code'=>4,'data'=>'','msg'=>'修改失败']);
    }
}